<template>
  <div class="container">
    <el-form ref="formRef" :model="form" :rules="rules" v-loading="loading" label-width="150px">
      <el-divider content-position="left"><span class="title-left-color">基本信息</span></el-divider>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="分配时间：" prop="distribute_time">
            <el-date-picker v-model="form.distribute_time" type="date" format="YYYY/MM/DD" value-format="x" placeholder="选择分配日期"></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="left"><span class="title-left-color">投资商列表</span></el-divider>
      <el-space wrap class="mb20">
        <el-button type="primary" :icon="Plus" :disabled="disabledbtn" @click="handleAddData">新增</el-button>
        <el-popconfirm placement="top" width="160" title="你确定要删除吗?" @confirm="batchDeleteData">
          <template #reference>
            <el-button type="danger" :icon="Delete" :disabled="disabledbtn">批量删除</el-button>
          </template>
        </el-popconfirm>
      </el-space>
      <el-table :data="form.investor_allocate_list" border class="table" ref="selectMultipleTableRef" :reserve-selection="true">
        <el-table-column type="index" align="center"> </el-table-column>
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="investors.company_name" label="投资商" align="center"> </el-table-column>
        <el-table-column prop="money" label="投资金额" align="center">
          <template #default="scope">
            <div class="">
              <el-input v-model.trim="scope.row.money" placeholder="请输入内容"></el-input>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="分配优先级" align="center">
          <template #default="scope">
            <div class="">
              <el-input v-model="scope.row.priority" placeholder="请输入内容"></el-input>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="investors.actual_investment_amount" label="可投资金额" align="center"> </el-table-column>
        <el-table-column prop="investors.enterprise_alipay_account_balance" label="企业支付宝余额" align="center"> </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <div class="mlr10 display-inline-block">
              <el-popconfirm placement="top" width="160" title="你确定要删除吗?" @confirm="handleDeleteData(scope.row)">
                <template #reference>
                  <el-button link :icon="Delete" type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <div class="footer-center">
      <el-button :disabled="disabledbtn" @click="cancelSubmit">取 消</el-button>
      <el-button type="primary" :disabled="disabledbtn" v-if="!isDisabledbtn" @click="submitForm">确 定</el-button>
    </div>
  </div>
  <!-- 选择投资商 -->
  <SelectInvestorsDialog v-model:editVisible="editVisible" @handleSuccess="handleSelectSuccess" />
</template>

<script setup lang="ts">
import SelectInvestorsDialog from "@/components/user/investorsManager/allocateInvestors/SelectInvestorsDialog.vue";

import { Delete, Plus } from "@element-plus/icons-vue";
import type { postOrPutType } from "@/constants";
import type { HasId, ViewMode } from "@/types/common";
import type { TableInstance } from "element-plus";
import { useState } from "@/hooks/useState.ts";
import type { IAllocateInvestors, IInvestorAllocateItem } from "@/types/user/allocateInvestors";
import { commonInvestorAllocateRuleInfo, getInvestorAllocateRuleByIdInfo } from "@/utils/api/admin/merchant/investorAllocateRule";
import type { IInvestorsInfoVo } from "@/types/user/investorsInfo";
const { disabledbtn, loading, toggleState } = useState();
interface Props {
  id: number;
}
const { id } = defineProps<Props>();
const formStatus = defineModel<ViewMode>("formStatus", { required: true });

const emit = defineEmits<{
  handleInitData: [];
  handleSuccess: [];
}>();
const isDisabledbtn = ref(false);
const editVisible = ref(false);
const formRef = useTemplateRef("formRef");
const selectMultipleTableRef = ref<TableInstance>();
const methodType = ref<postOrPutType>("PUT");
const form = reactive<IAllocateInvestors>({
  id: 0,
  distribute_time: 0,
  investor_allocate_list: []
});
const rules = reactive({
  distribute_time: [{ required: true, message: "请填写分配时间", trigger: "blur" }]
});

/* formStatus处理器 */
const statusHandlers: Record<ViewMode, () => void> = {
  view: () => {
    isDisabledbtn.value = true;
  },
  edit: () => {
    methodType.value = "PUT";
  },
  add: () => {
    methodType.value = "POST";
  },
  none: () => {
    /* 初始化数据 */
    handleInitData();
  }
};
/* 监听formStatus,新增，编辑，查看的时候都可以打开模态框，又是有不同的操作和效果，需要单独判断，none为模态框关闭的情况，需要初始化数据 */
watch(formStatus, newValue => {
  const handler = statusHandlers[newValue];
  handler?.();
});
/*  */
watch(
  () => id,
  newValue => {
    if (newValue == 0) {
      /* 初始化数据 */
    } else {
      form.id = newValue;
      handleGetDataByIdInfo(id);
    }
  }
);

/* 获取详情信息 */
function handleGetDataByIdInfo(id: number) {
  toggleState(true);
  getInvestorAllocateRuleByIdInfo<IAllocateInvestors, HasId>({ id })
    .then(res => {
      form.id = res.result.id;
      form.distribute_time = res.result.distribute_time * 1000;
      form.investor_allocate_list = res.result.investor_allocate_list;
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}
/* 初始化数据 */
function handleInitData() {
  methodType.value = "POST";
  isDisabledbtn.value = false;

  form.id = 0;
  form.investor_allocate_list = [];
  formRef.value?.resetFields();
  formRef.value?.clearValidate();
}

/* 保存或编辑 */
function submitForm() {
  if (!formRef.value) return;
  formRef.value.validate(valid => {
    if (!valid) {
      ElMessage.warning("请填写必填字段");
      return;
    }
    submitFormInfo();
  });
}

/* 保存或编辑信息 */
function submitFormInfo() {
  /* 防止多次提交 */
  toggleState(true);
  commonInvestorAllocateRuleInfo(form, methodType.value)
    .then(res => {
      ElMessage.success(res.msg);
      cancelSubmit();
      emit("handleSuccess");
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}
/* 保存或编辑 取消提交 */
function cancelSubmit() {
  // clearData();
  // activeName = "one";
  emit("handleInitData");
}

/* 打开模态框选择新增商品 */
function handleAddData() {
  editVisible.value = true;
}
/* 批量删除商品信息 */
function batchDeleteData() {
  let selection = selectMultipleTableRef.value!.store.states.selection.value;
  if (selection.length === 0) {
    ElMessage.warning("请至少选择一条数据");
    return;
  }
  for (const item of selection) {
    handleDeleteData(item);
  }
}
/* 删除信息 */
function handleDeleteData(row: IInvestorAllocateItem) {
  console.log(row);
  console.log(form.investor_allocate_list);

  const index = form.investor_allocate_list.findIndex((item: IInvestorAllocateItem) => item.investor_id === row.investor_id);
  if (index != -1) {
    form.investor_allocate_list.splice(index, 1);
  }
}

/* 选中数据 */
function handleSelectSuccess(data: IInvestorsInfoVo[]) {
  for (const item of data) {
    if (!handleIsSelectedData(item)) {
      handleAddDataList(item);
    }
  }
}
/* 判断 是否已经选中过了*/
function handleIsSelectedData(item: IInvestorsInfoVo) {
  for (let i = 0; i < form.investor_allocate_list.length; i++) {
    if (form.investor_allocate_list[i].investor_id === item.id) {
      return true;
    }
  }
  return false;
}
/* 添加数据 */
function handleAddDataList(item: IInvestorsInfoVo) {
  let obj: IInvestorAllocateItem = {
    id: 0,
    investor_id: item.id,
    money: "",
    priority: 0,
    investors: {
      id: item.id,
      company_name: item.company_name,
      actual_investment_amount: item.actual_investment_amount,
      enterprise_alipay_account_balance: item.enterprise_alipay_account_balance
    }
  };
  form.investor_allocate_list.push(obj);
}
</script>

<style lang="scss" scoped>
/* 修改select的盒模型 */
.el-select {
  display: block;
}
/* 底部按钮居中 */
.footer-center {
  margin: 10px 0;
  text-align: center;
}
</style>
